package com.zhugang.week14.jvm;

import java.lang.reflect.Field;
import java.net.URLClassLoader;
import java.util.List;

/**
 * @program geek-jvm
 * @description: 显示当前加载器加载了哪些jar
 * @author: chanzhugang
 * @create: 2021/03/27 14:55
 */
public class JvmClassLoaderPrintPath {

    public static void main(String[] args) {

       /* URL[] urLs = Launcher.getBootstrapClassPath().getURLs();
        System.out.println("启动类加载器");
        for (URL urL : urLs) {
            System.out.println("===>" + urL.toExternalForm());
        }*/
        // 扩展类加载器
        printClassLoader("扩展类加载器", JvmClassLoaderPrintPath.class.getClassLoader().getParent());
        // 应用类加载器
        printClassLoader("应用类加载器", JvmClassLoaderPrintPath.class.getClassLoader());

    }

    private static void printClassLoader(String name, ClassLoader cl) {
        if (null != cl) {
            System.out.println(name + "ClassLoader ->" + cl.toString());
            printURLForClassLoader(cl);
        } else {
            System.out.println(name + "ClassLoader -> null");
        }

    }

    private static void printURLForClassLoader(ClassLoader cl) {
        Object ucp = insightField(cl, "ucp");
        List paths = (List) insightField(ucp, "path");
        for (Object path : paths) {
            System.out.println("==>" + path.toString());
        }

    }

    private static Object insightField(Object object, String fName) {
        Field field;

        try {
            if (object instanceof URLClassLoader) {
                field = URLClassLoader.class.getDeclaredField(fName);
            } else {
                field = object.getClass().getDeclaredField(fName);
            }
            field.setAccessible(true);
            return field.get(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}